package org.xs.web.http;

import java.io.IOException;

import org.xs.web.http.provider.HTTPHeader;
import org.xs.web.http.provider.HTTPResponse;

public class AjaxResponse implements XSResponse{
	private String contentType;
	private int code;
	private HTTPHeader[] headers;
	private String ajax;
	
	public AjaxResponse(String ajax,String contentType,int code,HTTPHeader[] headers){
		this.contentType = contentType;
		this.code = code;
		this.headers = headers;
		this.ajax = ajax;
	}
	
	public AjaxResponse(String ajax,String contentType,int code){
		this(ajax,contentType,code,new HTTPHeader[0]);
	}
	
	public AjaxResponse(String ajax,int code){
		this(ajax,"application/x-javascript;charset=utf-8",code,new HTTPHeader[0]);
	}
	public AjaxResponse(String ajax,int code,HTTPHeader[] headers){
		this(ajax,"application/x-javascript;charset=utf-8",code,headers);
	}
	
	public AjaxResponse(String ajax){
		this(ajax,"application/x-javascript;charset=utf-8",200,new HTTPHeader[0]);
	}
	
	public AjaxResponse(int code,HTTPHeader[] headers){
		this(null,"application/x-javascript;charset=utf-8",code,headers);
	}
	
	public AjaxResponse(HTTPHeader[] headers){
		this(null,"application/x-javascript;charset=utf-8",304,headers);
	}
	
	@Override
	public Object apply(HTTPResponse response) {
		response.addHeader(XSRules.defaultHeaders());
		response.addHeader(headers);
		response.setStatus(code);
		response.addHeader("Content-Type", contentType);
		if(code == 304 && ajax == null){
			
		}else{
			try {
				response.getDelegate().getWriter().write(ajax);
			} catch (IOException e) {
				 
			}
		}
		return true;
	}

	@Override
	public int getCode() {
		return code;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public HTTPHeader[] getHeaders() {
		return headers;
	}

	@Override
	public boolean isJs() {
		return true;
	}

	@Override
	public boolean isStream() {
		return false;
	}

	@Override
	public boolean isTemplete() {
		return false;
	}

	@Override
	public boolean isText() {
		return false;
	}

	@Override
	public boolean isXml() {
		return false;
	}

}
